import config from '@/config/config'

/**
 * @function request
 * @param {string} url - 接口前缀，默认值为config.baseUrl 也支持其他例如config.baseUrl2
 * @param {string} api - 接口地址
 * @param {string} method 默认值为GET，method支持GET POST PUT DELETE等方法(请注意各个平台兼容性)
 * @param {string} data - 参数
 * @param {string} contentType - 默认为json，也支持form (application/x-www-form-urlencoded)
 * @return {Promise} 返回Promise对象
 * @description 封装uniapp的request
 * @author zhaoyongqiang
 *
 */

export default function request(api, method = 'GET', data = {}, contentType = 'json',url = config.baseUrl) {
	const {
		headerKey,
		headerValue
	} = config;
	let header = {
		'content-type': 'application/json'
	};

	if (contentType === 'form') {
		header = {
			'content-type': 'application/x-www-form-urlencoded'
		};
	}

	if (headerKey && headerValue) {
		header = {
			...header,
			[headerKey]: headerValue
		};
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: url + api,
			method,
			header,
			data,
			success: (res) => {
				if (res.statusCode === 200) {
					if (typeof config.showErrorMessage(res.data) === 'undefined') {
						resolve(res.data);
					} else {
						reject(res.data);
						uni.showModal({
							title: '提示',
							content: config.showErrorMessage(res.data),
							showCancel: false
						})
					}
				} else if (res.statusCode === 401) {
					// 登录过期
					uni.clearStorageSync();
					uni.reLaunch({
						url: config.loginPage
					});
				} else if (res.statusCode >= 500) {
					uni.showToast({
						title: '服务器错误',
						icon: 'error',
						duration: 2500
					});
				}
			},
			fail: (err) => {
				// 请求失败 timeout 或者无网络等 域名错误等
				reject(err);
				uni.showToast({
					title: '无法连接到服务器',
					icon: 'error',
					duration: 2500
				});
			}
		});
	});
}